package com.shopping.service.impl;
import com.shopping.mapper.OrderDescMapper;
import com.shopping.mapper.OrderMapper;
import com.shopping.model.Car;
import com.shopping.model.OrderDesc;
import com.shopping.model.Orders;
import com.shopping.service.CarService;
import com.shopping.service.OrderService;
import com.shopping.utils.GenerateOrderId;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
@Service
@Transactional //声明式事务，使用该注解，当前类中所有方法，都属于一个独立的事务
public class OrderServiceImpl implements OrderService {

    @Resource
    private CarService carService;
    @Resource
    private OrderDescMapper orderDescMapper;
    @Resource
    private OrderMapper orderMapper;
    /**
     * 添加订单
     *  1.补全订单及其相关属性
     *  2.向数据库添加订单和订单明细
     *  3.从redis中删除已购买商品
     * @param orders
     * @param orderDescList
     * @throws Exception
     */
    @Override
    public void addOrder(Orders orders, List<OrderDesc> orderDescList) throws Exception {
        orders.setOrder_id(GenerateOrderId.getOrderId());//订单编号
        double total = 0;
        //遍历orderDescList并添加订单明细相关属性数据
        for (OrderDesc orderDesc:orderDescList){
            //设置订单编号
            orderDesc.setOrder_id(orders.getOrder_id());
            //从redis中读取购物车数据
            Car car = carService.getCarInfoById(orders.getUser_id(), orderDesc.getBook_id());
            //设置购买数量
            orderDesc.setCount(car.getCar_count());
            total=total+car.getCar_count()*car.getBook_price();
        }
        //设置订单总价格
        orders.setOrder_total_price(total);

        //向数据库添加数据
        orderMapper.addOrder(orders);
        orderDescMapper.addOrderDesc(orderDescList);

        //从redis中删除购买商品
        for (OrderDesc orderDesc:orderDescList){
            carService.delCarByBookId(orders.getUser_id(),orderDesc.getBook_id());
        }
    }
}
